<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <el-input v-model="classifyNameOfTree" size="small"
                  placeholder="请输入产品分类" clearable
                  prefix-icon="el-icon-search"
                  @keyup.enter.native="handleSelectClassifyOfTree"
        />

        <el-tree style="margin-top: 20px"
                 :props="{label:'classifyName'}"
                 :data="classifyTreeOptions"
                 :expand-on-click-node="false"
                 :filter-node-method="filterClassifyTreeNode"
                 @node-click="handleClassifyNodeClick"
                 ref="classifyTree"
                 default-expand-all
        />
      </el-col>

      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="系列名称" prop="seriesName">
            <el-input
              v-model="queryParams.seriesName"
              placeholder="请输入系列名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="状态"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                       v-hasPermi="['product:series:query']"
            >搜索
            </el-button>
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                       v-hasPermi="['product:series:add']"
            >新增
            </el-button>
            <el-button type="warning" icon="el-icon-download" size="mini" v-hasPermi="['product:series:export']"
                       @click="handleExport"
            >导出
            </el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="seriesList" border>
          <el-table-column prop="classifyName" label="所属分类" align="center"/>
          <el-table-column prop="seriesName" label="系列名称" align="center"/>
          <el-table-column prop="status" label="状态" width="100" :formatter="statusFormat" align="center"/>
          <el-table-column prop="createBy" label="创建者" width="160" align="center" :show-overflow-tooltip="true"/>
          <el-table-column prop="createTime" label="创建时间" align="center" width="160"/>
          <el-table-column v-if="false" prop="deptName" label="组织名称" width="150" :show-overflow-tooltip="true"/>
          <el-table-column label="操作" align="center" width="150">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['product:series:edit']"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['product:series:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :before-close="closeDialogConfirm">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属分类" prop="classifyId">
              <treeselect v-model="form.classifyId" :options="classifyTreeOptions" :show-count="true"
                          placeholder="请选择所属分类" :normalizer="classifyTreeSelectNormalizer"
                          :flat="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="系列名称" prop="seriesName">
              <el-input v-model="form.seriesName" placeholder="请输入系列名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属组织" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptTreeOptions" :show-count="true"
                          placeholder="请选择归属组织" disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addSeries,
  deleteSeries,
  exportSeriesList,
  getClassifyList,
  getSeriesList,
  updateSeries
} from '@/api/system/productManage'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { deptTreeSelect } from '@/api/system/dept'

export default {
  name: 'index',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 字典表格数据
      seriesList: [],
      deptTreeOptions: [],
      selectedClassifyId: undefined,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // add/update
      operationType: '',
      // 状态数据字典
      statusOptions: [],
      // 产品分类树
      classifyTreeOptions: [],
      // 搜索的产品分类名称
      classifyNameOfTree: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        seriesName: undefined,
        classifyId: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      rules: {
        seriesName: [
          { required: true, message: '系列名称不能为空', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '归属组织不能为空', trigger: 'blur' }
        ],
        classifyId: [
          { required: true, message: '所属分类不能为空', trigger: 'blur' }
        ],
        orderNum: [
          { required: true, message: '显示排序不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    classifyNameOfTree(value) {
      if (!value || value === '') {
        this.queryParams.classifyId = undefined
      }
    }
  },
  created() {
    this.getSeriesList()
    this.getClassifyTree()
    this.getDeptTreeOptions()
    this.getDictDataByType('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
  },
  methods: {
    getSeriesList() {
      this.loading = true
      getSeriesList(this.queryParams).then(response => {
        this.seriesList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询部门下拉树结构 */
    getDeptTreeOptions() {
      deptTreeSelect().then(response => {
        this.deptTreeOptions = response.data
      })
    },
    /** 查询产品分类树 */
    getClassifyTree() {
      getClassifyList().then(response => {
        let treeListNoRoot = this.handleTree(response.rows, 'id')
        let rootNode = {
          id: 0,
          classifyName: '全部',
          children: []
        }
        rootNode.children = JSON.parse(JSON.stringify(treeListNoRoot))
        let treeOptions = []
        treeOptions.push(rootNode)
        this.classifyTreeOptions = treeOptions
      })
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        seriesName: undefined,
        classifyId: undefined,
        orderNum: 1,
        status: '0',
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getSeriesList()
    },
    handleAdd() {
      this.reset()
      this.operationType = 'add'
      this.open = true
      this.title = '添加产品系列'
      this.form.deptId = 100
      if (this.selectedClassifyId) {
        this.form.classifyId = this.selectedClassifyId
      }
    },
    handleUpdate(row) {
      this.reset()
      this.operationType = 'update'
      this.open = true
      this.title = '修改产品系列'

      let selectedSeries = this.seriesList.find(item => {
        return item.id === row.id
      })
      if (selectedSeries) {
        this.form = { ...selectedSeries }
      }
    },
    handleDelete(row) {
      this.$confirm('是否删除产品系列"' + row.seriesName + '"?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSeries(row.id).then(response => {
          this.getSeriesList()
        })
      }).then(() => {
        this.msgSuccess('删除成功')
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.operationType === 'add') {
            addSeries(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('添加成功')
                this.open = false
                this.getSeriesList()
              }
            })
          }
          if (this.operationType === 'update') {
            updateSeries(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getSeriesList()
              }
            })
          }
        }
      })
    },
    // 筛选产品分类树节点
    filterClassifyTreeNode(value, data) {
      if (!value) return true
      return data.classifyName.indexOf(value) !== -1
    },
    // 点击树节点
    handleClassifyNodeClick(data) {
      this.classifyNameOfTree = data.classifyName
      this.queryParams.classifyId = data.id
      this.selectedClassifyId = data.id
      this.handleQuery()
    },
    handleSelectClassifyOfTree() {
      this.$refs.classifyTree.filter(this.classifyNameOfTree)
      this.queryParams.classifyId = undefined
      this.handleQuery()
    },
    // 自定义treeselect的标签名
    classifyTreeSelectNormalizer(node) {
      return {
        id: node.id,
        label: node.classifyName,
        children: node.children,
        isDisabled: node.id === 0
      }
    },

    /**
     * 对话框确认关闭
     */
    closeDialogConfirm() {
      this.$confirm('确认关闭?').then(() => {
        this.open = false
      }).catch(() => {
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return exportSeriesList(this.queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    }
  }
}
</script>

<style scoped>

</style>
